package com.chixing.service.impl;

import com.chixing.entity.MongDB.Post;
import com.chixing.entity.MongDB.Reply;
import com.chixing.repository.PostRepository;
import com.chixing.repository.ReplyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PostService {

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private ReplyRepository replyRepository;

    /**
     * 新增主楼
     */
    public Post addPost(Post post) {
        post.setIsDeleted(1); // 默认未删除
        post.setCreateTime(LocalDateTime.now());
        return postRepository.save(post);
    }

    /**
     * 获取主楼详情 + 构建楼中楼树
     */
    public Post getPostDetail(String postId) {
        Post post = postRepository.findById(postId).orElse(null);
        if (post == null) {
            return null;
        }

        // 查询所有回复（已按 path 排序）
        List<Reply> replies = replyRepository.findByPostIdOrderByPathAsc(postId);

        // 构建树
        post.setReplies(buildTree(replies));

        return post;
    }

    /**
     * 将平铺的 reply 列表组装成树形
     */
    private List<Reply> buildTree(List<Reply> replies) {

        // 使用 Map 加速父子关联
        Map<String, Reply> map = new HashMap<>();
        List<Reply> roots = new ArrayList<>();

        // 初始化 children 并放入 map
        for (Reply r : replies) {
            r.setChildren(new ArrayList<>()); // 初始化子节点
            map.put(r.getId(), r);
        }

        // 挂载子节点
        for (Reply r : replies) {
            if (r.getParentId() == null || r.getParentId().isEmpty()) {
                // 顶级回复，直接挂到根列表
                roots.add(r);
            } else {
                Reply parent = map.get(r.getParentId());
                if (parent != null) {
                    parent.getChildren().add(r); // 挂到父节点 children
                } else {
                    // 异常处理：父节点找不到，归根节点
                    roots.add(r);
                }
            }
        }

        return roots;
    }

    public List<Post> getAllPosts() {
        return postRepository.findByIsDeleted(1); // 只返回未删除的
    }


}
